package csc.fresher.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import csc.fresher.dao.UserDAOImpl;
import csc.fresher.domain.User;

/**
 * Servlet implementation class RegisterServlet
 */

public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RegisterServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("inputName");
		String password = request.getParameter("inputPassword");
		if (username.equals("") || password.equals("")) {
			if (username.equals(""))
				request.setAttribute("messageUsername",
						"Please insert username. Username not null");
			if (password.equals(""))
				request.setAttribute("messagePassword",
						"Please insert password. Password not null");
			request.getRequestDispatcher("register.jsp").forward(request,
					response);
		} else {
			if (username.length() < 5 || password.length() < 8) {
				if (username.length() < 5)
					request.setAttribute("messageUsername",
							"Username must be at least 5 character in length");
				if (password.length() < 8)
					request.setAttribute("messagePassword",
							"Password must be at least 8 character in length");
				request.getRequestDispatcher("register.jsp").forward(request,
						response);
			} else {
				String regex = "\\w+";
				if (!username.matches(regex)) {
					request.setAttribute("messageUsername",
							"Username only contain word and digit");
					request.getRequestDispatcher("register.jsp").forward(request,
							response);
				} else {
					UserDAOImpl dao = new UserDAOImpl();
					if (dao.checkUser(username)) {
						request.setAttribute("messageUserExist",
								"User are exist");
						request.getRequestDispatcher("register.jsp").forward(
								request, response);
					} else {
						User user = new User(username, password, false);
						dao.addUser(user);
						request.setAttribute("messageRegisterSuccess",
								"Congratulation ! You register success");
						request.getRequestDispatcher("index.jsp").forward(
								request, response);
					}
				}
			}
		}
	}
}
